package com.lap.web.starter.ip;

import com.lap.web.starter.ip.valueobject.UserAgentInfo;
import lombok.experimental.UtilityClass;
import ua_parser.Client;
import ua_parser.Parser;

@UtilityClass
public class UserAgentParser {

  private static final Parser PARSER = createParser();

  private static Parser createParser() {
    try {
      return new Parser();
    } catch (Exception e) {
      return null;
    }
  }

  public static UserAgentInfo parse(String userAgent) {
    if (PARSER == null || userAgent == null) {
      return UserAgentInfo.unknown();
    }

    Client c = PARSER.parse(userAgent);

    String os = c.os.family;
    String browser = c.userAgent.family;
    String version = version(c.userAgent.major, c.userAgent.minor);
    String device = c.device.family;

    return new UserAgentInfo(os, browser, version, device);
  }

  private static String version(String major, String minor) {
    if (major == null) return "";
    return (minor == null) ? major : major + "." + minor;
  }
}
